var variableData;
$(document).ready(function () {
	$.ajax({
        type: 'POST',
        async: false,
        url: 'repository/database/getSimpleList.shtml',
        data: {},
        success: function (data) {
        	for (var i=0; i<data.length; i++){
        		$("#jobRepositoryId").append('<option value="' + data[i].repositoryId + '">' + data[i].repositoryName + '</option>');
        	}
        },
        error: function () {
            alert("请求失败！请刷新页面重试");
        },
        dataType: 'json'
    });	 
	$.ajax({
        type: 'POST',
        async: false,
        url: 'quartz/getSimpleList.shtml',
        data: {},
        success: function (data) {
        	for (var i=0; i<data.length; i++){
        		$("#jobQuartz").append('<option value="' + data[i].quartzId + '">' + data[i].quartzDescription + '</option>');
        	}
        },
        error: function () {
            alert("请求失败！请刷新页面重试");
        },
        dataType: 'json'
    });	
	$.ajax({
        type: 'POST',
        async: false,
        url: 'variable/getSimpleList.shtml',
        data: {},
        success: function (data) {
            variableData = data;
        },
        error: function () {
            alert("请求失败！请刷新页面重试");
        },
        dataType: 'json'
    }); 
	$("#customerQuarz").cronGen({
    	direction : 'left'
	});	
	initFileInput("jobFile", "job/uploadJob.shtml");
});
//初始化fileinput控件（第一次初始化）
function initFileInput(ctrlName, uploadUrl) {    
    var control = $('#' + ctrlName); 
    control.fileinput({
        language: 'zh', //设置语言
        uploadUrl: uploadUrl, //上传的地址
        allowedFileExtensions: ['kjb'],//接收的文件后缀
        uploadAsync: true, //默认异步上传
        showUpload: false, //是否显示上传按钮
        showCaption: true,//是否显示标题
        dropZoneEnabled: false,//是否显示拖拽区域
        browseClass: "btn btn-primary", //按钮样式             
        previewFileIcon: "<i class='glyphicon glyphicon-king'></i>", 
    });
}
$("#jobFile").on("filebatchselected", function(event, files) {
	$("#jobFile").fileinput("upload");
	$(".kv-upload-progress").hide();
});
$("#jobFile").on("fileuploaded", function(event, data, previewId, index) {
	$("#jobPath").val(data.response.data);
});

$("#changeQuartz").click(function(){
	$("#default").toggle();
	$("#custom").toggle();
	$("#jobQuartz").val("");
	$("#customerQuarz").val("");
});

$("#addVariable").click(function(){
    if (variableData && variableData.length != 0) {
        addVariable(variableData[0].variableId);
    }
});

var addVariable = function(variableId){
    $("#variableValueTbody").append($("#variableTemplate").html());
    if (variableData && variableData.length != 0) {
        var addVariableObject;
        var variableValueSelectOptions = "";
        for (var i=0; i<variableData.length; i++){
            variableValueSelectOptions += "<option data-variable-type=\""+variableData[i].variableType+"\" data-variable-value=\""+variableData[i].variableValue+"\" data-variable-name=\""+variableData[i].variableName+"\" value=\""+variableData[i].variableId+"\">"+variableData[i].variableDescription+"</option>";
            if (variableId == variableData[i].variableId) {
                addVariableObject = variableData[i];
            }
        }
        if (!addVariableObject) {
            return;
        }
        var lastVariableIdSelect = $("#variableValueTbody").find(".defaultVariable").last();
        lastVariableIdSelect.append(variableValueSelectOptions);
        lastVariableIdSelect.children("option[value="+addVariableObject.variableId+"]").attr("selected", true);
        var tr = lastVariableIdSelect.parent().parent();
        var variableInput = tr.find(".variableInput").attr('disabled',true);
        var variableType = tr.find("[data-name=variableType]");
        variableType.children("[value="+addVariableObject.variableType+"]").attr("selected", true);
        var variableName = tr.find("[data-name=variableName]");
        variableName.val(addVariableObject.variableName);
        var variableDescription = tr.find("[data-name=variableDescription]");
        variableDescription.val(addVariableObject.variableDescription);
        var variableValue = tr.find("[data-name=variableValue]");
        variableValue.val(addVariableObject.variableValue);
        
        lastVariableIdSelect.on('change', function(){
            var variableIdSelect = lastVariableIdSelect;
            var variableInputRef = variableInput;
            var variableTypeRef = variableType;
            var variableNameRef = variableName;
            var variableDescriptionRef = variableDescription;
            var variableValueRef = variableValue;
            
            var selectedOption = $(this).children(":selected");
            
            variableValueRef.val(selectedOption.attr('data-variable-value'));
            variableTypeRef.children("[value="+selectedOption.attr('data-variable-type')+"]").attr("selected", true);
            variableNameRef.val(selectedOption.attr('data-variable-name'));
            variableDescriptionRef.val(selectedOption.html());
            variableInputRef.attr('disabled',true);
            
        });
        
        tr.find(".change-variable-input-type").on('click', function(){
            var variableIdSelect = lastVariableIdSelect;
            var variableInputRef = variableInput;
            var variableTypeRef = variableType;
            var variableNameRef = variableName;
            var variableValueRef = variableValue;
            
            if (variableIdSelect.children(":selected").val()) {
                variableValueRef.show();
                variableIdSelect.children(":selected").removeAttr("selected");
                variableIdSelect.val("");
                variableIdSelect.hide();
                variableInputRef.removeAttr('disabled');
            } else {
                variableValueRef.val(addVariableObject.variableValue);
                variableValueRef.hide();
                variableTypeRef.children("[value="+addVariableObject.variableType+"]").attr("selected", true);
                variableNameRef.val(addVariableObject.variableName);
                variableInputRef.attr('disabled',true);
                variableIdSelect.show();
                variableIdSelect.children(":selected").removeAttr("selected");
                variableIdSelect.children("[value="+addVariableObject.variableId+"]").attr("selected", true);
            }
        });
        
        tr.find(".del-variable").on('click', function(){
            var parentTr = tr;
            parentTr.remove();
        });
        
    }
}

$.validator.setDefaults({
	highlight: function (element) {
        $(element).closest('.form-group').removeClass('has-success').addClass('has-error');
    },
    success: function (element) {
        element.closest('.form-group').removeClass('has-error').addClass('has-success');
    },
    errorElement: "span",
    errorPlacement: function (error, element) {
        if (element.is(":radio") || element.is(":checkbox")) {
            error.appendTo(element.parent().parent().parent());
        } else {
            error.appendTo(element.parent());
        }
    },
    errorClass: "help-block m-b-none",
    validClass: "help-block m-b-none"	
});
$().ready(function () {
    var getVariable = function(){
        var variableArr = [];
        var variableIdArrObj = {};
        var variableNameArrObj = {};
        var validata = true;
        $("#variableValueTbody").children("tr").each(function(){
            var tr = $(this);
            var param = {};
            var variableId = tr.find("[data-name=variableId]");
            if (variableId.val()) {
                if (variableIdArrObj[variableId.val()]) {
                    validata = false;
                    return false;
                }
                variableIdArrObj[variableId.val()] = 1;
                $.extend(param,{"variableId":variableId.val()});
            }
            
            var variableName = tr.find("[data-name=variableName]");
            if (variableNameArrObj[variableName.val()]) {
                validata = false;
                return false;
            }
            variableNameArrObj[variableName.val()] = 1;
            
            var variableType = tr.find("[data-name=variableType]");
            var variableValue = tr.find("[data-name=variableValue]");
            $.extend(param,{"variableType":variableType.val(),"variableName":variableName.val(),"variableValue":variableValue.val()});
            variableArr.push(param);
        });
        if (validata == false) {
            return null;
        }
        return variableArr;
    };
    var icon = "<i class='fa fa-times-circle'></i> ";
    $("#RepositoryJobForm").validate({
        rules: {
        	jobName: {
        		required: true,
        		maxlength: 50
        	},
        	jobLogLevel: {
        		required: true,
        	},
        	jobDescription: {
        		maxlength: 500
        	}
        },
        messages: {
        	jobName: {
        		required: icon + "请输入作业名称",
        		maxlength: icon + "作业名称不能超过50个字符"
        	},
        	jobLogLevel: {
        		required: icon + "请选择作业的日志记录级别",
        	},
        	jobDescription: {
        		maxlength: icon + "作业描述不能超过500个字符"
        	}
        },
        submitHandler:function(form){
            var params = {};
            var variableArr = getVariable();
            if (variableArr == null) {
                alert("不能存在相同的作业参数！");
                return false;
            }
            
            $.extend(params, {"variableArrJson":JSON.stringify(variableArr)});
            $.extend(params, $(form).serializeObject());
        	$.post("job/insert.shtml", params, function(data){
        		var result = JSON.parse(data);
    			if(result.status == "success"){
    				layer.msg('添加成功',{
            			time: 2000,
            			icon: 6
            		});              		
            		setTimeout(function(){
            			location.href = "view/job/listUI.shtml";
            		},2000);
    			}else {
    				layer.msg(result.message, {icon: 2}); 
    			}
    		});
        } 
    });
});

$.fn.serializeObject = function()
{
    var o = {};
    var a = this.serializeArray();
    $.each(a, function() {
        if (o[this.name] !== undefined) {
            if (!o[this.name].push) {
                o[this.name] = [o[this.name]];
            }
            o[this.name].push(this.value || '');
        } else {
            o[this.name] = this.value || '';
        }
    });
    return o;
};

var cancel = function(){
	location.href = "view/job/listUI.shtml";   	
}